import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

import java.io.IOException;
import java.util.Arrays;

/**
 * lucene测试类
 *
 * @author wly
 * @date 2018/8/28 17:11
 */
public class Test {
    public static void main(String[] args) throws IOException, ParseException {
        // 分词器
        Analyzer analyzer = new StandardAnalyzer();
        // 索引存储对象，内存索引
        Directory directory = new RAMDirectory();
        // 索引写入配置类，配置分词器
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

        try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
            // 添加一个文档
            Document document = new Document();
            String text = "This is the text to be indexed";
            document.add(new Field("fieldName", text, TextField.TYPE_STORED));
            indexWriter.addDocument(document);
            indexWriter.close();

            // 从索引存储对象中读取索引
            DirectoryReader directoryReader = DirectoryReader.open(directory);
            // 索引搜索
            IndexSearcher indexSearcher = new IndexSearcher(directoryReader);
            // 搜索解析器
            QueryParser queryParser = new QueryParser("fieldName", analyzer);
            // 搜索条件
            Query query = queryParser.parse("text");
            // 执行搜索，并设置返回结果是最大值
            ScoreDoc[] scoreDocs = indexSearcher.search(query, 1000).scoreDocs;
            // 遍历打印搜索结果
            Arrays.stream(scoreDocs).forEach(scoreDoc -> {
                try {
                    System.out.println("doc：" + scoreDoc.doc + "，shardIndex：" +scoreDoc.shardIndex + "，score：" +  scoreDoc.score);
                    Document hitDocument = indexSearcher.doc(scoreDoc.doc);
                    System.out.println(hitDocument.get("fieldName"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            directoryReader.close();
            directory.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
